package com.collect.tanzania.zhiHelper;

import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Base64;

import com.collect.tanzania.MyApplication;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class ZHIFileHelper {

    public static final String TAG = "EDGEBOXFileDistributor";

    public static String getImageDir() {

        String imgDir = MyApplication.getApp().getApplicationContext().getFilesDir() + "/HooImages";

        File dirFile = new File(imgDir);
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }

        return imgDir;
    }

    public static String getImageFilePath() {

        String pictureId = (System.currentTimeMillis() + "");
        String imgDir = getImageDir();
        String imgPath = imgDir + "/" + pictureId + ".jpg";

        return imgPath;
    }

    public static String getPDFFilePath() {

        String pictureId = (System.currentTimeMillis() + "");

        String imgDir = getImageDir();
        String imgPath = imgDir + "/" + pictureId + ".pdf";

        return imgPath;
    }

    public static String getImageAbsolutePath(Context context, Uri imageUri, boolean isBitTest) {
        if (context == null || imageUri == null) {
            return null;
        }

        if (Build.VERSION.SDK_INT >= 29) {
            return getBitmapFilePathFromURI(context, imageUri);
        }

        if (isBitTest) {
            return getRealPathFromURI(context, imageUri);
        }

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT && DocumentsContract.isDocumentUri(context, imageUri)) {
            if (isExternalStorageDocument(imageUri)) {
                String docId = DocumentsContract.getDocumentId(imageUri);
                String[] split = docId.split(":");
                String type = split[0];
                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }
            } else if (isDownloadsDocument(imageUri)) {
                String id = DocumentsContract.getDocumentId(imageUri);
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
                return getDataColumn(context, contentUri, null, null);
            } else if (isMediaDocument(imageUri)) {
                String docId = DocumentsContract.getDocumentId(imageUri);
                String[] split = docId.split(":");
                String type = split[0];
                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }
                String selection = MediaStore.Images.Media._ID + "=?";
                String[] selectionArgs = new String[]{split[1]};
                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        } // MediaStore (and general)
        else if ("content".equalsIgnoreCase(imageUri.getScheme())) {
            // Return the remote address
            if (isGooglePhotosUri(imageUri))
                return imageUri.getLastPathSegment();
            return getDataColumn(context, imageUri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(imageUri.getScheme())) {
            return imageUri.getPath();
        }
        return null;
    }

    public static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
        Cursor cursor = null;
        String column = MediaStore.Images.Media.DATA;
        String[] projection = {column};
        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }

    public static String getRealPathFromURI(Context context, Uri contentURI) {
        String result;
        Cursor cursor = null;
        try {
            cursor = context.getContentResolver().query(contentURI, null, null, null, null);
        } catch (Throwable e) {
            e.printStackTrace();
        }
        if (cursor == null) {
            result = contentURI.getPath();
        } else {
            cursor.moveToFirst();
            int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
            result = cursor.getString(idx);
            cursor.close();
        }
        return result;
    }

    public static String getBitmapFilePathFromURI(Context context, Uri contentURI) {

        try {
            InputStream imgInputStream = context.getContentResolver().openInputStream(contentURI);
            if (imgInputStream == null) {
                return "";
            }

            Bitmap bitmap = BitmapFactory.decodeStream(imgInputStream);
            if (bitmap == null) {
                return "";
            }

            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);

            String outFilePath = getImageFilePath();
            File outFile = new File(outFilePath);

            FileOutputStream fos = new FileOutputStream(outFile);
            fos.write(stream.toByteArray());
            fos.flush();
            fos.close();
            stream.flush();
            stream.close();
            imgInputStream.close();

            return outFilePath;

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "";
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is Google Photos.
     */
    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }

    public static Bitmap getBitMapFromBytes(byte[] bytes) {
        Bitmap bitmap = null;
        try {
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inPreferredConfig = Bitmap.Config.ARGB_8888;
            bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length, options);
        } catch (ArrayIndexOutOfBoundsException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return bitmap;
    }

    public static Bitmap getFileBitmap(String filePath) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;
        Bitmap gBitmap = BitmapFactory.decodeFile(filePath, options);
        return gBitmap;
    }

    public static File getBitmapFile(Bitmap bitmap) throws IOException {
        if (bitmap == null) {
            return null;
        }

        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        try {
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
        } catch (Exception e) {
            e.printStackTrace();
        }

        String targetPath = ZHIFileHelper.getImageFilePath();
        File outFile = new File(targetPath);

        FileOutputStream fos = new FileOutputStream(outFile);
        fos.write(stream.toByteArray());
        fos.flush();
        fos.close();
        stream.flush();
        stream.close();

        return outFile;
    }

    public static String getBitmapFilePath(Bitmap bitmap){
        String targetPath = "";
        try {
            if (bitmap == null) {
                return targetPath;
            }

            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);

            targetPath = ZHIFileHelper.getImageFilePath();
            File outFile = new File(targetPath);

            FileOutputStream fos = new FileOutputStream(outFile);
            fos.write(stream.toByteArray());
            fos.flush();
            fos.close();
            stream.flush();
            stream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return targetPath;
    }

    public interface ImageFileCalculateListener {
        void onSuccess(String localPath, String extension, Bitmap thumpImg);
    }

    public static void calculateIamgeFile(final Context context, File file, final ImageFileCalculateListener onImageFileCalculateListener) {
//        try {
//            String suffix = extSuffix(file);
//            String targetDir = ZHIFileHelper.getImageDir();
//            String targetPath = targetDir + "/" +
//                    System.currentTimeMillis() +
//                    (TextUtils.isEmpty(suffix) ? ".jpg" : suffix);
//
//            File outFile = new File(targetPath);
//
//            File result = KACEHESAPOcrChecker.SINGLE.needCompress(230, file.getAbsolutePath()) ?
//                    new KACEHESAPOcrCompressUtil(file, outFile, false).compress() :
//                    file;
//
//            String localPath = result.getAbsolutePath();
//            String extension = (TextUtils.isEmpty(suffix) ? "jpg" : suffix).replace(".", "").trim();
//            Bitmap thumpBitmap = getFileBitmap(localPath);
//
//            if (onImageFileCalculateListener != null) {
//                onImageFileCalculateListener.onSuccess(localPath, extension, thumpBitmap);
//            }
//            //扫描到相册
//            MediaScannerConnection.scanFile(context, new String[]{localPath}, null, null);
//
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
    }

    public static String extSuffix(File file) {
        try {
            FileInputStream input = new FileInputStream(file);
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(input, null, options);
            return options.outMimeType.replace("image/", ".");
        } catch (Exception e) {
            return ".jpg";
        }
    }

    public static String convertBitmapToBase64(Bitmap bitmap) {
        String result = null;
        ByteArrayOutputStream baos = null;
        try {
            if (bitmap != null) {
                baos = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);

                baos.flush();
                baos.close();

                byte[] bitmapBytes = baos.toByteArray();
                result = Base64.encodeToString(bitmapBytes, Base64.NO_WRAP);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (baos != null) {
                    baos.flush();
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    public static String convertImageToBase64(String path) {
        if (TextUtils.isEmpty(path)) {
            return null;
        }
        InputStream is = null;
        byte[] data = null;
        String result = null;
        try {
            is = new FileInputStream(path);
            //创建一个字符流大小的数组。
            data = new byte[is.available()];
            //写入数组
            is.read(data);
            //用默认的编码格式进行编码
            result = Base64.encodeToString(data, Base64.NO_WRAP);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
        return result;
    }
}
